﻿namespace FFF.Test.Entity.Web
{
    using System;
    using System.IO;
    using System.Linq;

    /// <summary>
    /// This class is used to find root path of the web project in;
    /// unit tests (to find views) and entity framework core command line commands (to find conn string).
    /// </summary>
    public static class WebContentDirectoryFinder
    {
        /// <summary>
        /// 获取floder
        /// </summary>
        /// <returns>web项目地址</returns>
        public static string CalculateContentRootFolder()
        {
            var coreAssemblyDirectoryPath = Path.GetDirectoryName(AppContext.BaseDirectory);
            if (coreAssemblyDirectoryPath == null)
            {
                throw new FileNotFoundException("Could not find location of FFF.Test.Entity assembly!");
            }

            var directoryInfo = new DirectoryInfo(coreAssemblyDirectoryPath);
            while (!DirectoryContains(directoryInfo.FullName, "FFF.Test.sln"))
            {
                if (directoryInfo.Parent == null)
                {
                    throw new FileNotFoundException("Could not find content root folder!");
                }

                directoryInfo = directoryInfo.Parent;
            }

            return Path.Combine(directoryInfo.FullName, $"src{Path.DirectorySeparatorChar}FFF.Test");
        }

        /// <summary>
        /// 文件夹是否村子
        /// </summary>
        /// <param name="directory">目录的名称</param>
        /// <param name="fileName">文件的名称</param>
        /// <returns>是否存在</returns>
        private static bool DirectoryContains(string directory, string fileName)
        {
            return Directory.GetFiles(directory).Any(filePath => string.Equals(Path.GetFileName(filePath), fileName, StringComparison.Ordinal));
        }
    }
}
